﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace neside2
{
    /// <summary>
    /// Default_TextEdit.xaml 的交互逻辑
    /// </summary>
    public partial class Default_TextEdit : UserControl
    {
        public Default_TextEdit()
        {
            InitializeComponent();
        }
        class Doc : IDE.IDocument
        {
            public UIElement Editor
            {
                get;
                set;
            }

            public string Filename
            {
                get;
                set;
            }

            public bool writeable;
            public bool Save()
            {
                if (!writeable) return false;

                return (Editor as Default_TextEdit).Save();
            }
            public event Action Change;
            public void DoChange()
            {
                Change?.Invoke();
            }
        }
        string Fullname;
        Doc thisdoc;

        public IDE.IDocument OpenFile(string filename, bool writeable)
        {
            this.editor.Text = System.IO.File.ReadAllText(filename);
            if (!writeable)
                this.editor.IsReadOnly = true;
            else
            {
                this.editor.TextChanged += (s, e) =>
                  {
                      this.thisdoc.DoChange();
                  };
            }
            this.Fullname = filename;
            thisdoc = new Doc();
            thisdoc.Editor = this;
            thisdoc.Filename = filename;
            thisdoc.writeable = writeable;
            return thisdoc;
        }
        public bool Save()
        {
            try
            {
                System.IO.File.Delete(thisdoc.Filename);
                System.IO.File.WriteAllText(thisdoc.Filename, editor.Text);
                return true;
            }
            catch (Exception err)
            {
                return false;
            }
        }
    }
}
